package com.doge.calcalbum.db

import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import com.doge.calcalbum.db.model.Album
import com.doge.calcalbum.db.model.Entry
import com.doge.calcalbum.db.model.Note

@Database(
    entities = [Album::class, Entry::class, Note::class],
    version = 3
)
abstract class CalcDB : RoomDatabase() {
    abstract fun albumDao(): AlbumDao
    abstract fun entryDao(): EntryDao
    abstract fun noteDao(): NoteDao

    companion object {
        private var INSTANCES = mutableMapOf<Int, CalcDB>()
        private val key: Int get() = 1 // 固定
        private fun databaseName() = "calc.db"

        fun getInstance(
            context: Context
        ) =
            INSTANCES[key] ?: synchronized(this) {
                INSTANCES[key] ?: buildDatabase(context).also {
                    INSTANCES[key] = it
                }
            }

        private fun buildDatabase(
            context: Context
        ) =
            Room.databaseBuilder(context.applicationContext, CalcDB::class.java, databaseName())
                .fallbackToDestructiveMigration()
                .build()
    }
}

